<template>
  <a-popover
    v-model="visible"
    trigger="click"
    placement="bottomRight"
    overlayClassName="header-notice-wrapper"
    :getPopupContainer="() => $refs.noticeRef.parentElement"
    :autoAdjustOverflow="true"
    :arrowPointAtCenter="true"
    :overlayStyle="{ width: '300px', top: '50px' }"
  >
    <template slot="content">
      <a-spin :spinning="loading">
        <a-tabs v-model="activeKey" @change="handleChange">
          <a-tab-pane tab="消息" :key="1">
            <Notify ref="Notify" />
          </a-tab-pane>
          <a-tab-pane tab="待办" :key="2">
            <PersonalTask ref="PersonalTask" />
          </a-tab-pane>
          <a-tab-pane tab="预警" :key="3">
            <Warning ref="Warning" />
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </template>
    <span @click="handleOpen" class="header-notice" ref="noticeRef" style="padding: 0 18px">
      <a-badge :count="count">
        <a-icon style="font-size: 16px; padding: 4px" type="bell" />
      </a-badge>
    </span>
  </a-popover>
</template>

<script>
import store from '@/store'
import Notify from './components/Notify'
import PersonalTask from './components/PersonalTask'
import Warning from './components/Warning'
export default {
  name: 'HeaderNotice',
  components: {
    Notify,
    PersonalTask,
    Warning
  },
  data () {
    return {
      activeKey: 1,
      loading: false,
      visible: false,
      count: 0,
      interval: null
    }
  },
  watch: {
    '$store.getters.notifyCount': function (n) {
      this.count = n || 0
    }
  },
  created() {
    this.getNotifyCount(0)
    this.startInterval()
  },
  methods: {
    handleOpen() {
      this.visible = !this.visible
      if (this.visible) {
        this.$nextTick(() => {
          this.handleFilter()
        })
      }
    },
    handleChange(key) {
      this.handleFilter()
    },
    handleFilter() {
      if (1 === this.activeKey) {
        this.$nextTick(() => {
          this.$refs.Notify.getList()
        })
      } else if (2 === this.activeKey) {
        this.$nextTick(() => {
          this.$refs.PersonalTask.getList()
        })
      } else if (3 === this.activeKey) {
        this.$nextTick(() => {
          this.$refs.Warning.getList()
        })
      }
    },
    async getNotifyCount(count) {
      await this.$store.dispatch('getNotifyCount', count)
    },
    async startInterval() {
      if (this.interval) {
        clearInterval(this.interval)
      }
      const ticks = 10 * 1000
      this.interval = setInterval(async () => {
        this.getNotifyCount()
      }, ticks)
    }
  }
}
</script>

<style lang="css">
  .header-notice-wrapper {
    top: 50px !important;
  }
  .no-focus:focus {
    text-decoration: none;
  }
</style>
<style lang="less" scoped>
  .header-notice{
    display: inline-block;
    transition: all 0.3s;

    span {
      vertical-align: initial;
    }
  }
</style>
